Page({
  /**
   * 页面的初始数据
   */
  // 本地存储
  // key: 'nextList', storeNextAllList, hotText


  // 手机端在input框存在的时候点击搜索按钮，input失去焦点的事件会在搜索按钮的事件之后执行-bug，尝试更改成keyup事件
  data: {
    hot: "",
    inputText: "",
    items: [],
    initNum: 1,
    ADDNUM: 20,
    allItemData: "",
    opacity: 0,

    hotHeight: "114rpx",
    hotTextToggle: "展开",
    HotAllHeight: "",

    getAutoAll: [],
    autoAll: false,

    autoTime: 0,

    tab: 0,
    setTabData: [{
        id: 0,
        title: "搜索"
      },
      {
        id: 1,
        title: "榜单"
      },
      {
        id: 2,
        title: "书单"
      },
      {
        id: 3,
        title: "分类"
      },
      {
        id: 4,
        title: "记录"
      },
    ],

    jl: "",

    // 书单数据
    bookList: []


  },

  openHotText() {
    if (this.data.hotTextToggle === "展开") {
      this.setData({
        hotHeight: this.data.HotAllHeight,
        hotTextToggle: "收起"
      })
    } else {
      this.setData({
        hotHeight: "114rpx",
        hotTextToggle: "展开"
      })
    }
  },

  inputBlur() {
    this.setData({
      autoAll: false
    })
  },

  inputFocus() {
    this.setData({
      autoAll: true
    })
  },

  sendBQlist(e) {
    this.setData({
      items: []
    })
    this.getItemData(e.currentTarget.dataset.value)
  },

  getInputText(e) {
    this.setData({
      inputText: e.detail.value
    })

    if (e.detail.value === "") {
      this.setData({
        autoAll: false
      })
    } else {
      this.getAutoAll(e.detail.value);
    }
    // 这是一个小bug
  },
  getAutoAll(value) {
    let that = this;
    wx.request({
      url: `https://api.zhuishushenqi.com/book/auto-complete?query=${value}`,
      success: function(res) {
        that.setData({
          getAutoAll: res.data.keywords
        })
        that.setData({
          autoAll: true
        })
      }
    })
  },

  getBookListData1() {
    if (!this.data.inputText) {
      return
    }
    this.setData({
      items: []
    })
    this.getItemData(this.data.inputText)
  },
  getBookListData2(e) {
    this.setData({
      items: []
    })
    this.getItemData(e.currentTarget.dataset.value)
  },

  getItemData(text) {
    this.setData({
      initNum: 1
    })
    let url = `https://api.zhuishushenqi.com/book/fuzzy-search?query=${text}`;
    let that = this;
    wx.request({
      url: url,
      success: function(res) {
        wx.hideNavigationBarLoading() // 隐藏loading状态
        res.data.books.map(function(val) {
          let src = val.cover.indexOf("http");
          src = decodeURIComponent(val.cover.substring(src)); // 解码状态
          val.cover = src;
        }); // 将图片的地址转为可以用的地址

        if (!res.data.books.length) {
          that.setData({
            items: ""
          })
        } else {
          that.setData({
            items: res.data.books.slice(0, 20)
          })
          wx.setStorage({ // 添加本地存储
            key: 'nextList',
            data: res.data.books.slice(0, 20)
          })
          wx.setStorage({
            key: 'storeNextAllList',
            data: res.data.books
          })
          // that.data.allItemData = res.data.books;
          that.setData({
            allItemData: res.data.books
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.getHotData();
    this.pushListData();
  },

  pushListData() {
    const nextList = wx.getStorageSync("nextList");
    if (nextList) {
      this.setData({
        items: nextList
      })
    } else {
      this.getItemData('系统');
    }
  },

  getHotData() {
    const value = wx.getStorageSync('hotText')
    if (value) {
      this.setData({
        hot: value
      })
    } else {
      let that = this;
      this.requestHotData(that);
    }
  },

  requestHotData(that) {
    wx.request({
      url: "https://api.zhuishushenqi.com/book/search-hotwords",
      success: function(res) {
        that.setData({
          hot: res.data.searchHotWords
        })
        wx.setStorage({
          key: 'hotText',
          data: that.data.hot
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    this.obtainHotHeight();

    let autoTime = setTimeout(this.undataHotText, 15000);
    this.setData({
      autoTime
    })

    this.setStorageJl()


    this.getGenderData() // 获取gender初始数据

    this.getBookListData() // 获取书单初始数据

    this.getRecordData() // 获取分类初始数据
  },

  getRecordData() { // 获取分类初始数据
    const appData = getApp()
    wx.request({
      url: 'https://api.zhuishushenqi.com/cats/lv2/statistics',
      success: res => {
        appData.setRecord(res.data);
      }
    })
  },

  getBookListData() {
    const appData = getApp()
    wx.request({
      url: 'https://api.zhuishushenqi.com/book-list',
      success: res => {
        let resData = res.data.bookLists;
        resData.forEach(val => {
          if (val.gender === "male") {
            val.gender = "男生专区"
          } else {
            val.gender = "女生专区"
          }

          let http = val.cover.indexOf("http");
          http = val.cover.slice(http);
          val.cover = decodeURIComponent(http);
          
          for(let i = 0; i < val.covers.length; i++) {
            let ehttp = val.covers[i].indexOf("http");
            val.covers[i] = decodeURIComponent(val.covers[i].slice(ehttp))
          }

          // val.covers.forEach(eval => {
          //   console.log(eval)
          //   // let ehttp = eval.indexOf("http");
          //   // eval = decodeURIComponent(eval.slice(ehttp));
          // })
        })
        appData.setbookList(res.data.bookLists)
      }
    })
  },

  getGenderData() { // 获取gender初始数据
    let that = this
    const appData = getApp()
    wx.request({
      url: 'https://api.zhuishushenqi.com/ranking/gender',
      success: res => {
        let arr = [];
        for (let key in res.data) {
          let obj = {};
          if (res.data.ok) {
            delete res.data.ok;
          }
          if (key === "male") {
            obj.name = "男生专区"
            obj.data = res.data[key];
            this.addImgInArr(res.data[key])
          } else if (key === "female") {
            obj.name = "女生专区"
            obj.data = res.data[key];
            this.addImgInArr(res.data[key])
          } else if (key === "picture") {
            obj.name = "出版专区"
            obj.data = res.data[key];
            this.addImgInArr(res.data[key])
          } else if (key === "epub") {
            obj.name = "电子书专区"
            obj.data = res.data[key];
            this.addImgInArr(res.data[key])
          }
          arr.push(obj);
        }
        arr.sort((a, b) => {
          return b.data.length - a.data.length
        })

        appData.setranking(arr)
      }
    })
  },

  addImgInArr(res) {
    res.forEach(val => {
      val.img = `/static/${val.shortTitle}.png`
    })
  },



  setStorageJl() {
    if (!wx.getStorageSync("jl")) {
      wx.setStorage({
        key: "jl",
        data: [],
      })
    }
  },
  obtainHotHeight() {
    var query = wx.createSelectorQuery();
    query.select('.hot').boundingClientRect(); // 选中dom
    let that = this;
    query.exec(function(res) {
      that.setData({
        HotAllHeight: res[0].height * 14 + "rpx" // 这里的问题还没得到解决
      })
    })
  },

  undataHotText() {
    let that = this;
    wx.request({
      url: "https://api.zhuishushenqi.com/book/search-hotwords",
      success: function(res) {
        let flog = false;
        const value = wx.getStorageSync('hotText')
        for (let i = 0; i < res.data.searchHotWords.length; i++) {
          if (value[i].word !== res.data.searchHotWords[i].word) {
            flog = true;
          }
        }
        if (flog) {
          wx.showModal({
            title: '提示',
            content: 'hot热搜词有更新，是否更新',
            confirmText: '确定',
            cancelText: '取消',
            success: function(text) {
              if (text.confirm) {
                that.setData({
                  hot: res.data.searchHotWords
                })
                wx.setStorage({
                  key: 'hotText',
                  data: that.data.hot,
                })
              } else if (text.cancel) {
                return
              }
            }
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    console.log("")
    this.jlEvent()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    clearTimeout(this.data.autoTime)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    const appData = getApp()
    if (this.data.tab === 0) {
      wx.showNavigationBarLoading()
      let random = Math.floor(Math.random() * 100);
      this.getItemData(this.data.hot[random].word)

    }
    else if (this.data.tab === 2) {
      wx.showNavigationBarLoading()
      this.countdown = this.selectComponent('#bklist');
      this.countdown.getInitData(appData.globalData.bookList)
      wx.hideNavigationBarLoading()
    } else {
      return
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    this.data.initNum++;
    let bigNum = this.data.initNum * this.data.ADDNUM;
    const storeNextAllList = wx.getStorageSync("storeNextAllList")

    if (bigNum >= storeNextAllList.length + this.data.ADDNUM) {
      if (!this.data.opacity) {
        this.setData({
          opacity: 1
        });
        let that = this;
        setTimeout(function() {
          that.setData({
            opacity: 0
          });
        }, 3000)
      }
      return
    }
    this.setData({
      items: storeNextAllList.slice(0, bigNum)
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  pushBookIntro(e) {
    if (this.data.autoTime) {
      clearTimeout(this.data.autoTime)
    }
    wx.navigateTo({
      url: `/pages/bookIntro/intro-start/index?id=${e.currentTarget.dataset.id}`
    })
    // console.log(e.currentTarget.dataset.id)
  },

  addTagNumber(e) { // 底部切换页面
    // this.selectComponent()  
    if (this.data.autoTime) {
      clearTimeout(this.data.autoTime)
    }
    this.setData({
      tab: parseInt(e.detail)
    })
  },

  jlEvent() {
    // 如果记录模块显示，则将jl的数据进行设置，然后记录模块接收并渲染
    let jl = wx.getStorageSync("jl");
    this.setData({
      jl: jl
    })
  },


  removeStorageJl() { // 点击删除 jl Storage数据时刷新界面
    this.jlEvent()
  }
  // ----------------------------------------
})